package com.example.dao;

import com.example.pojo.Equipment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class EquipDao {
    //查看所有器材、查看所有空闲器材
    public List<Equipment> selectEquipments(Boolean flag)
    {
        //true为查询所有,false为查询空闲
        JdbcTemplate template=new JdbcTemplate(DataBaseUtils.getDataSource());
        String sql="SELECT * FROM equipment ";
        if(!flag)
            sql+=" WHERE free_count>0";
        return template.query(sql, new RowMapper<Equipment>() {
            @Override
            public Equipment mapRow(ResultSet resultSet, int i) throws SQLException {
                Equipment equipment=new Equipment();
                equipment.setId(resultSet.getInt(1));
                equipment.setName(resultSet.getString(2));
                equipment.setDate(resultSet.getDate(3));
                equipment.setCount(resultSet.getInt(4));
                equipment.setFree_count(resultSet.getInt(5));
                return equipment;
            }
        });
    }
    //使用器材、归还器材
    public Boolean useEquip(Integer id,Boolean flag)
    {
        //true为使用,false为归还
        JdbcTemplate template=new JdbcTemplate(DataBaseUtils.getDataSource());
        String sql;
        if(flag) sql="UPDATE equipment SET free_count=free_count-1 WHERE id=?";
        else sql="UPDATE equipment SET free_count=free_count+1 WHERE id=?";
        return template.update(sql,id)>0;
    }
    //增加器材
    public Boolean addEquip(Equipment equipment)
    {
        JdbcTemplate template=new JdbcTemplate(DataBaseUtils.getDataSource());
        //默认初始剩余数量等于总数量
        String sql="INSERT INTO equipment(name,date,count,free_count)" +
                "VALUES(?,?,?,?)";
        return template.update(sql,
                equipment.getName(),
                equipment.getDate(),
                equipment.getCount(),
                equipment.getCount())>0;
    }
    //删除器材
    public Boolean deleteEquip(Integer id)
    {
        JdbcTemplate template=new JdbcTemplate(DataBaseUtils.getDataSource());
        String sql="DELETE FROM equipment WHERE id=?";
        return template.update(sql, id)>0;
    }

}
